package Commands;

import javax.servlet.http.HttpServletRequest;

public class CommandFactory
{

  public CommandFactory()
  {
    //naught?
  }

  //Returns an instance of a specific command.
  // presumably init() has not been run yet.

  public Command getCommand(HttpServletRequest req)
  {
    try
    {
      //Instantiates the specific command sub-class and returns it as such.
      return (Command) getCmdClass(req).newInstance();
    }
    catch (IllegalAccessException e)
    {
      // TODO
    }
    catch (InstantiationException e)
    {
      // TODO
    }
    return null; //delete me when exceptions are handled
  }

  // This is where the dynamic part really takes place.
  // concatenates the command attribute with path and returns  
  // some sort of reference to the Command super-class - though
  // it isn't instantiated yet. Not at all sure of the inner workings here.

  private Class getCmdClass(HttpServletRequest req)
  {

    Class result = null;
    String command = null;
    if (req.getParameter("command") == null && req.getAttribute("command") == null)
      command = "CmdDefault";
    else
      if(req.getAttribute("command")!=null)
        command = (String)req.getAttribute("command");
      else
        command = req.getParameter("command");
    String cmdName = "Commands." + command;
    //LogObj.log().severe("Processing Command: '" + command + "' from " +        req.getRemoteAddr());
    try
    {
      result = Class.forName(cmdName);
    }
    catch (ClassNotFoundException e)
    {
      //LogObj.log().severe("Command '" + command + "' from " +   req.getRemoteAddr() + " not found.");
    }
    return result;
  }
}
